package com.game.sdk.handle;

import com.coment.dto.ApiNotify;
import com.coment.po.UserInfo;
import com.game.dao.living.AnchorInfoDao;
import com.game.dao.user.UserDao;
import com.game.logic.roles.RolesService;
import com.game.sdk.ApiNotifyEvent;
import com.xs.action.exection.ActionException;
import com.xs.build.server.websocket.channel.ClientManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class CreateChain {
    @Resource
    private RolesService rolesService;
    @Resource
    private AnchorInfoDao anchorInfoDao;
    @Resource
    private UserDao userDao;
    @Resource
    private ApplicationEventPublisher eventPublisher;

    public void tryCreateChain(ApiNotify body) {
        String roomId = body.getRoomId();
        Integer anchorInfoId = this.anchorInfoDao.searchByApiTypeAndRoomId(
                body.getApiType().getValue(),
        roomId).orElseThrow(
                () -> new ActionException("不存在主播信息")
        ).getId();

        body.setAnchorInfoId(anchorInfoId);

        try {
            UserInfo userInfo = body.getUserInfo();
            userInfo.setId(userInfo.hashCode());
            userInfo = userDao.tryCreateUser(userInfo);
            body.setUserInfo(userInfo);
            Integer userInfoId = userInfo.getId();
            this.rolesService.tryObtainFreeRole(userInfoId,anchorInfoId);
        } catch (Exception e) {
            log.error("BarrageOperationChain error", e);
        } finally {
            eventPublisher.publishEvent(new ApiNotifyEvent(this, body));
            ClientManager.sendMessageToClient(anchorInfoId, body);
        }
    }
}
